import Vue from 'vue'
import Vuex from 'vuex'

import {INCREMENT} from './mutilation-types'

//1.安装插件
Vue.use(Vuex)

//2.创建Vuex对象
const moduleA = {
  state: {
    name: '杨'
  },
  mutations: {
    updateName(state, payload) {
      state.name = payload
    }
  },
  actions: {
    aUpdateName(context) {
      setTimeout(() => {
        context.commit('updateName', '美杨杨')
      }, 1000)
    }
  },
  getters: {
    fullName(state) {
      return state.name + '先生'
    },
    fullName2(state, getters) {
      return getters.fullName + '您好'
    },
    fullName3(state, getters, rootState) {
      return getters.fullName2 + rootState.counter
    }
  }
}

const store = new Vuex.Store({
  state: {
    counter: 1000,
    students: [
      {id: 110, name: '杨美霞', age: 19},
      {id: 111, name: '李宇超', age: 20},
      {id: 112, name: '杨杨美美霞霞', age: 21},
      {id: 113, name: '美美霞霞杨杨', age: 22},
    ],
    info: {
      name: '杨美霞',
      age: 23,
      height: 1.61
    }
  },
  mutations: {
    //定义方法
    [INCREMENT](state) {
      state.counter++
    },
    decrement(state) {
      state.counter--
    },
    incrementCount(state, count) {
      state.counter += count
    },
    addStudent(state, stu) {
      state.students.push(stu)
    },
    updateInfo(state) {
      state.info.name = 'ymx'
      //不能在这里进行异步操作
      // setTimeout(() => {
      //   state.info.name = 'ymx'
      // }, 1000)

      //state.info['address] = '天津'

      // Vue.set(state.info, 'address', '天津')
      //delete state.info.age
      // Vue.delete(state.info, 'age')
    }
  },
  actions: {
    //context 上下文
    // aUpdateInfo(context, payload) {
    //   setTimeout(() => {
    //     context.commit('updateInfo')
    //     console.log(payload.message)
    //     payload.success()
    //   }, 1000)
    // }

    aUpdateInfo(context, payload) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          context.commit('updateInfo')
          console.log(payload);
          resolve('success')
        }, 1000)
      })
    }
  },
  getters: {
    powerCounter(state) {
      return state.counter * state.counter
    },
    more20stu(state) {
      return state.students.filter(s => s.age > 20)
    },
    more20stuLength(state, getters) {
      return getters.more20stu.length
    },
    moreAgeStu(state) {
      // return function (age) {
      //   return state.students.filter(s => s.age > age)
      // }
      return age => {
        return  state.students.filter(s => s.age > age)
      }
    }
  },
  modules: {
    a: moduleA
  }
})

//3.到处store
export default store
